package com.example.demomk.Fragment;



import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.RecyclerView;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.example.demomk.Adapter.DetailsAdapter;
import com.example.demomk.Interface.OnBottomBarListener;
import com.example.demomk.Interface.OnDialogButtonClickListener;
import com.example.demomk.Interface.OnGeneratePDFListener;
import com.example.demomk.MainActivity;
import com.example.demomk.R;
import com.example.demomk.Repository.PDFRepository;
import com.example.demomk.Utils.CustomDialog;
import com.example.demomk.Utils.Dialogprint;
import com.example.demomk.Utils.StdDialogData;
import com.example.demomk.ViewModel.MeasurementViewModel;
import com.example.demomk.ViewModel.PdfViewModel;
import com.example.demomk.databinding.FragmentDetailsBinding;
import com.example.demomk.entity.AvgMeasurement;
import com.example.demomk.entity.Measurement;

import java.io.File;
import java.util.ArrayList;
import java.util.List;


public class DetailsFragment extends Fragment {
    private DetailsAdapter adapter;
    private RecyclerView recyclerView;
    private MeasurementViewModel viewmodel;
    private FragmentDetailsBinding  binding;

    private static final String ARG_PARAM1 = "param1";

    // 子 Fragment 实例缓存
    private ChildDetails childDetailsFragment;
    private ChildCount childCountFragment;
    private Fragment currentChildFragment;

    private int mParam1;
    private int currentpage;

    private CustomDialog dialogs;
    //打印dialog框
    private Dialogprint dialogPrint;
    private PdfViewModel pdfViewModel;
    private FragmentActivity activity;
    private int currentPage ;


    public DetailsFragment() {
        // Required empty public constructor
    }

    public static DetailsFragment newInstance(int param1) {
        DetailsFragment fragment = new DetailsFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_PARAM1, param1);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getInt(ARG_PARAM1);
        }
        if (mParam1 == 0){
            mParam1 = 1;
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = FragmentDetailsBinding.inflate(getLayoutInflater());
        return binding.getRoot();
    }
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
         activity = requireActivity();
        FragmentActivity fragmentActivity = activity;

        initView(fragmentActivity);

        setupTabListenners();

        setupDataObservation(fragmentActivity);
        setupInitialFragment(savedInstanceState);


        //点击事件
        detailsclick();
    }

    private void setupTabListenners() {

        TextView dataText = binding.dataText;
        TextView auditText = binding.auditText;
        dataText.setSelected(true);

        //tab切换
        dataText.setOnClickListener(v -> {
            if (!dataText.isSelected()) {
                dataText.setSelected(true);
                auditText.setSelected(false);
                switchTab(0);
            }

        });
        auditText.setOnClickListener(v -> {
            if (!auditText.isSelected()) {
                auditText.setSelected(true);
                dataText.setSelected(false);
                switchTab(1);
            }
        });
    }

    private void setupInitialFragment(Bundle savedInstanceState) {
        if (savedInstanceState == null) {
            childDetailsFragment = ChildDetails.newInstance(mParam1);
            getChildFragmentManager().beginTransaction()
                    .add(R.id.fragment_child, childDetailsFragment)
                    .commit();
            currentChildFragment = childDetailsFragment;
        } else {
            childDetailsFragment = (ChildDetails) getChildFragmentManager().findFragmentByTag(ChildDetails.class.getSimpleName());
            childCountFragment = (ChildCount) getChildFragmentManager().findFragmentByTag(ChildCount.class.getSimpleName());
        }
    }

    private void switchTab(int tabIndex) {
        Fragment toShowFragment;

        if (tabIndex == 0) {

            if (childDetailsFragment == null) {
                childDetailsFragment = ChildDetails.newInstance(mParam1);
                getChildFragmentManager().beginTransaction()
                        .add(R.id.fragment_child, childDetailsFragment, ChildDetails.class.getSimpleName())
                        .hide(childDetailsFragment)
                        .commitNow();
            }
            toShowFragment = childDetailsFragment;
        } else {
            if (childCountFragment == null) {
                childCountFragment = ChildCount.newInstance(mParam1,currentpage);
                getChildFragmentManager().beginTransaction()
                        .add(R.id.fragment_child, childCountFragment, ChildCount.class.getSimpleName())
                        .hide(childCountFragment)
                        .commitNow();
            }
            toShowFragment = childCountFragment;
        }

        if (currentChildFragment != null && currentChildFragment != toShowFragment) {
            getChildFragmentManager().beginTransaction()
                    .hide(currentChildFragment)
                    .show(toShowFragment)
                    .commitNow();
        }

        currentChildFragment = toShowFragment;
    }
    private void setupDataObservation(FragmentActivity fragmentActivity) {
        adapter(fragmentActivity, mParam1);
    }
    private void detailsclick() {
        //关闭当前页
        binding.icon.setOnClickListener(v -> {
            activity.getSupportFragmentManager().popBackStack();
        });

        if (activity instanceof OnBottomBarListener) {
            ((MainActivity) activity).setManageButtonListener(v -> {
                Toast.makeText(requireContext(), "details", Toast.LENGTH_SHORT).show();
            });
        }

        if (activity instanceof OnBottomBarListener) {
            ((OnBottomBarListener) activity).setPrintButtonListener(v -> {
                viewmodel.getAvgMeasurementWithDetails(mParam1).observe(activity, avg -> {
                    if (avg != null) {
                        List<Integer> ids = new ArrayList<>();
                        for (Measurement mes : avg.measurements) {
                            ids.add(mes.getId());
                        }
                        int start = ids.get(0);
                        int end = ids.get(ids.size() - 1);
                        dialogs = new CustomDialog(requireContext(), new OnDialogButtonClickListener() {
                            @Override
                            public void onConfirm( int start_page, int end_page) {
                                List<Integer> selectedId = new ArrayList<>();
                                selectedId.add(end_page);

                                //确定打印的dialog框
                                dialogPrint = new Dialogprint(requireContext(), new OnDialogButtonClickListener() {
                                    @Override
                                    public void onConfirm( int start_page, int end_page) {

                                    }
                                    @Override
                                    public void onCancel(int start_page, int end_page, String message,  StdDialogData data) {
                                        viewmodel.calculateStatsForAvgAsync(avg.avgMeasurement, statsList -> {
                                                    // 重新计算 stats
                                            viewmodel.getLocationStatsByAvgId(mParam1).observe(activity, pdfStatus -> {
                                                pdfViewModel.generatePDF(requireContext(), message, mParam1, new PDFRepository.OnPDFGeneratedListener() {
                                                    @Override
                                                    public void onSuccess(File file) {
                                                        //子线程，非UI线程
                                                        Log.d("PDF", "PDF 已生成：" + file.getName());
                                                    }
                                                    @Override
                                                    public void onError(Exception e) {
                                                        Toast.makeText(requireContext(), "生成失败：" + e.getMessage(), Toast.LENGTH_SHORT).show();
                                                    }
                                                },  statsList,pdfStatus);
                                            });
                                        });

                                    }
                                },selectedId,activity);
                                dialogPrint.show();
                            }
                            @Override
                            public void onCancel(int start_page, int end_page, String message,StdDialogData data) {

                            }
                        },start,end,mParam1,"数据导出");
                        dialogs.show();
                    }
                });
            });
        }
        //打印按钮
        if (activity instanceof OnBottomBarListener) {
            ((OnBottomBarListener) activity).setHomeButtonListener(v -> {
                Toast.makeText(requireContext(), "详情页打印按钮被点击", Toast.LENGTH_SHORT).show();
            });
        }
    }

    private void initView(FragmentActivity fragmentActivity) {
        pdfViewModel =  new ViewModelProvider(this).get(PdfViewModel.class);
        viewmodel = new ViewModelProvider(this).get(MeasurementViewModel.class);

        viewmodel.getMeasurementCount().observe(fragmentActivity, count -> {

            if (count != null) {
                currentpage = count;

            }
        });
    }

    private void adapter(FragmentActivity fragmentActivity,int mParam1) {

        viewmodel.getAllAvgMeasurementId(mParam1).observe(fragmentActivity, avgMeasurementWithDetails -> {
            binding.measurementname.setText(avgMeasurementWithDetails.getUser_name());
            String time = avgMeasurementWithDetails.getStart_time().split(" ")[0] ;
            String times = time +"\n" + time;
            binding.measurementtime.setText(times);
            binding.location.setText(avgMeasurementWithDetails.getLocation_name());
            binding.group.setText(avgMeasurementWithDetails.getGroup_name());
            binding.flow.setText(String.valueOf(avgMeasurementWithDetails.getFlow()) + "LPM");
        });



    }

    //切换子fragment方法
    private void addChildFragment(Fragment fragment) {

        // 使用ChildFragmentManager
        getChildFragmentManager().beginTransaction()
                .replace(R.id.fragment_child, fragment)
                .addToBackStack(null)
                .commit();
        currentChildFragment = fragment;
    }

    //切换fragment方法
//    private void loadFragment(Fragment fragment) {
//        activity.getSupportFragmentManager()
//                .beginTransaction()
//                .replace(R.id.fragment_container, fragment)
//                .addToBackStack(null)
//                .commit();
//    }

}